package com.zscat.mallplus.qsg.contrller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zscat.mallplus.annotation.SysLog;
import com.zscat.mallplus.qsg.ActivateRequest;
import com.zscat.mallplus.qsg.QsgGatewayInfo;
import com.zscat.mallplus.qsg.RegRequest;
import com.zscat.mallplus.qsg.service.IQsgGatewayInfoService;
import com.zscat.mallplus.util.MD5;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.UUID;

@Slf4j
@RestController
@Api(tags = "GatewaySetController", description = "网关设置")
@RequestMapping("/admin/gwCloud-platform/platform")
public class GatewaySetController {

    @Autowired
    private IQsgGatewayInfoService gatewayInfoService;

    @Value("${factory.secret}")
    private String factorySecret;

    @Value("${gateway.account}")
    private String gatewayAccount;

    @Value("${gateway.pwd}")
    private String gatewayPwd;

    @Value("${mainserverurl}")
    private String mainserverurl;

    @Value("${commandserverurl}")
    private String commandserverurl;

    @SysLog(MODULE = "gateway", REMARK = "网关管理")
    @PostMapping(value = "/gatewayInfoRegister/ServerReportPostInfoRegisterEachSign")
    @ResponseBody
    public Object registerGateway(@RequestBody RegRequest req) {
//        RegResponse response = new RegResponse();
        JSONObject response = new JSONObject();
        try {
            String mac = req.getMacno();
            String serialno = req.getSerialno();
            String installSecret = req.getInstallCode();
//            String factorySecret = "97abb862e38ed49c9dab8be5c3eb8a56";
            String chechCode = MD5.getMessageDigest(installSecret+factorySecret);
            QueryWrapper qw = new QueryWrapper();
            qw.eq("mac_addr",mac);
            QsgGatewayInfo gatewayInfo = gatewayInfoService.getOne(qw);
            if(null == gatewayInfo){
                gatewayInfo = new QsgGatewayInfo();
                String deviceId = UUID.randomUUID().toString();
                gatewayInfo.setCreateDatetime(new Date());
                gatewayInfo.setDeviceId(deviceId);
                gatewayInfo.setMacAddr(mac);
                gatewayInfo.setSerialno(serialno);
                boolean isOk = gatewayInfoService.save(gatewayInfo);
                if(isOk){
                    JSONObject resDetail = new JSONObject();
                    resDetail.put("DeviceId",deviceId);
                    resDetail.put("CheckCode",chechCode);
                    resDetail.put("Mac",mac);
                    log.info("网关注册响应信息:{}", JSON.toJSONString(resDetail));
                    response.put("RequestStatus","0");
                    response.put("Data",resDetail);
                }
            }else{
                JSONObject resDetail = new JSONObject();
                resDetail.put("DeviceId",gatewayInfo.getDeviceId());
                resDetail.put("CheckCode",chechCode);
                resDetail.put("Mac",gatewayInfo.getMacAddr());
                response.put("RequestStatus","0");
                response.put("Data",resDetail);
            }
            return response;
        } catch (Exception e) {
            log.error("注册网关失败：{}", e.getMessage());
            response.put("RequestStatus","100");
            response.put("Data",null);
            return response;
        }
    }


    @SysLog(MODULE = "gateway", REMARK = "网关管理")
    @PostMapping(value = "/gatewayInfoActivate/ServerReportPostInfoActivateEachPost")
    @ResponseBody
    public Object activateGateway(@RequestBody ActivateRequest req) {
        JSONObject response = new JSONObject();
        try {
            String deviceId = req.getDeviceId();
            //根据设备id查询设备详细信息
            String version = req.getVersion();
            QueryWrapper qw = new QueryWrapper();
            qw.eq("device_id",deviceId);
            QsgGatewayInfo gatewayInfo = gatewayInfoService.getOne(qw);
            if(null != gatewayInfo){
                JSONObject resDetail = new JSONObject();
                resDetail.put("DeviceId",gatewayInfo.getDeviceId());
                resDetail.put("Mac",gatewayInfo.getMacAddr());
                resDetail.put("SeriaIno",gatewayInfo.getSerialno());
//                resDetail.put("DeviceId",deviceId);
//                resDetail.put("Mac","18523D00019F");
//                resDetail.put("SeriaIno","18523D000000019F");
                resDetail.put("GatewayAccount",gatewayAccount);
                resDetail.put("Keyword",gatewayPwd);
                resDetail.put("MainServerUrl",mainserverurl);
                resDetail.put("CommandServerUrl",commandserverurl);
                resDetail.put("SubscribeTopic","/toGW/");
                resDetail.put("PublishTopic","/fromGW/");
                resDetail.put("ClientID",gatewayInfo.getMacAddr() + "_gateway");
                log.info("网关激活响应信息:{}", JSON.toJSONString(resDetail));
                response.put("RequestStatus","0");
                response.put("Data",resDetail);
            }
            return response;
        } catch (Exception e) {
            log.error("注册网关失败：{}", e.getMessage());
            response.put("RequestStatus","100");
            response.put("Data",null);
            return response;
        }
    }
}
